#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN 1024

int read_line(char * buffer, int max_len, FILE *fp)
{
    char temp;
    int i;
    int ret;
    for(i = 0; i < max_len; i++)
    {
        if((ret = read(&temp, 1, 1,fp)) < 0)
        {
            perror("read data error!");
            return -1;
        }
        if(ret == 0)
        {
            buffer[i] = '\0';
            return 0;
        }
        if(temp == '\n')
        {
            buffer[i] = temp;
            break;
        }
        buffer[i] = temp;
    }
    buffer[i + 1] = '\0';

    return i + 1;
}



//临时文件可以用W
int main(int argc, char ** argv)
{
    FILE * fp = NULL;
/* 定义一个缓冲区 */
    char buffer[MAX_LEN];
/* 打开文件 */
    fp = fopen(argv[1], "a+");
    if(fp == NULL)
    {
        printf(" open file error:%s\n",argv[1]);
        perror("open file error");      //会打印出错误原因
        exit(1);//和exit(0)什么区别
    }

    for(int i = 0; i < 3; i++)
    {
        memset(buffer, 0 , sizeof(buffer));
        gets(buffer);
        if(fwrite(buffer, 1, strlen(buffer), fp) < 0)
        {
            perror("open file error");      //会打印出错误原因
            exit(1);//和exit(0)什么区别
        }
        fwrite("\n", 1, 1, fp);
    }

    rewind(fp);
    memset(buffer, 0 , sizeof(buffer));

    while(read_line(buffer, MAX_LEN, fp) != 0)
    {
        printf("%s", buffer);
        memset(buffer, 0, sizeof(buffer));
    }

    fclose(fp);

    return 0;
}


